<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="品牌名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
          v-model="queryParams.contactInfo"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:brands:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:brands:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:brands:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:brands:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号"  align="center" type="index"/>
      <el-table-column label="品牌名称" align="center" prop="name" />
      <el-table-column label="品牌描述" align="center" prop="description" :show-overflow-tooltip="true"/>
      <el-table-column label="联系方式" align="center" prop="contactInfo" />
      <el-table-column label="官方网站" align="center" prop="website" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <a :href="scope.row.website" target="_blank">{{ scope.row.website }}</a>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleInfo(scope.row)"
            v-hasPermi="['business:brands:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:brands:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:brands:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电梯品牌管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input v-model="form.contactInfo" placeholder="请输入联系人/联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="品牌描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="6" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="官方网站" prop="website">
              <el-input v-model="form.website" placeholder="请输入官方网站链接" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">电梯型号管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddYtElevatorModels">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteYtElevatorModels">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="ytElevatorModelsList" :row-class-name="rowYtElevatorModelsIndex" @selection-change="handleYtElevatorModelsSelectionChange" ref="ytElevatorModels">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="名称" prop="name" width="180">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入名称" />
            </template>
          </el-table-column>
          <el-table-column label="型号名称" prop="model" width="180">
            <template slot-scope="scope">
              <el-input v-model="scope.row.model" placeholder="请输入型号名称" />
            </template>
          </el-table-column>
          <el-table-column label="类型" prop="type" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.type" placeholder="请选择类型" clearable>
                <el-option
                  v-for="dict in dict.type.bus_elevator_models_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="最大层数" prop="maxFloors" >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.maxFloors" placeholder="请输入最大层数" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="最大站数" prop="maxStops" >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.maxStops" :min="0" placeholder="请输入最大站数" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="最大门数" prop="maxDoors" >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.maxDoors" :min="0" placeholder="请输入最大门数" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="载重量（Kg）" prop="capacity" >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.capacity" :min="0"  placeholder="请输入载重量（Kg）" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="运行速度（米/秒）"  prop="speed" >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.speed" :step="0.1" :min="0" placeholder="请输入（多少米/秒）" controls-position="right"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改电梯品牌管理对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="80%" append-to-body :close-on-click-modal="false">
      <el-divider content-position="center">电梯品牌基本信息</el-divider>
      <el-descriptions border>
        <el-descriptions-item label="品牌名称">{{ form.name }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ form.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="官方网站">
          <a :href="form.website" target="_blank">{{ form.website }}</a>
        </el-descriptions-item>
        <el-descriptions-item label="品牌描述">{{ form.description }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="center">电梯型号信息</el-divider>
      <el-table :data="ytElevatorModelsList" ref="ytElevatorModels">
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="名称" prop="name" width="180"></el-table-column>
        <el-table-column label="型号名称" prop="model" width="180"></el-table-column>
        <el-table-column label="类型" prop="type" width="180">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.bus_elevator_models_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="最大层数" prop="maxFloors" ></el-table-column>
        <el-table-column label="最大站数" prop="maxStops" ></el-table-column>
        <el-table-column label="最大门数" prop="maxDoors" ></el-table-column>
        <el-table-column label="载重量（Kg）" prop="capacity" ></el-table-column>
        <el-table-column label="运行速度（米/秒）"  prop="speed" ></el-table-column>
        <el-table-column label="备注" prop="remark" ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBrands, getBrands, delBrands, addBrands, updateBrands } from "@/api/business/brands";

export default {
  name: "Brands",
  dicts: ['bus_elevator_models_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedYtElevatorModels: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电梯品牌管理表格数据
      brandsList: [],
      // 电梯型号管理表格数据
      ytElevatorModelsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        description: null,
        contactInfo: null,
        website: null,
        logoUrl: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询电梯品牌管理列表 */
    getList() {
      this.loading = true;
      listBrands(this.queryParams).then(response => {
        this.brandsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        brandId: null,
        name: null,
        description: null,
        contactInfo: null,
        website: null,
        logoUrl: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null
      };
      this.ytElevatorModelsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.brandId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电梯品牌管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const brandId = row.brandId || this.ids
      getBrands(brandId).then(response => {
        this.form = response.data;
        this.ytElevatorModelsList = response.data.ytElevatorModelsList;
        this.open = true;
        this.title = "修改电梯品牌管理";
      });
    },
    /** 修改按钮操作 */
    handleInfo(row) {
      this.reset();
      const brandId = row.brandId || this.ids
      getBrands(brandId).then(response => {
        this.form = response.data;
        this.ytElevatorModelsList = response.data.ytElevatorModelsList;
        this.openInfo = true;
        this.title = "电梯品牌信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查型号名称是否重复
          const modelNames = new Map();
          let duplicateIndexes = [];
          this.ytElevatorModelsList.forEach((model, index) => {
            if (modelNames.has(model.model)) {
              const existingIndex = modelNames.get(model.model);
              duplicateIndexes.push([existingIndex + 1, index + 1]); // 行号从1开始
            } else {
              modelNames.set(model.model, index);
            }
          });

          if (duplicateIndexes.length > 0) {
            const duplicateMessages = duplicateIndexes.map(([index1, index2]) => `第 ${index1} 行和第 ${index2} 行`);
            this.$modal.msgError(`型号名称在以下序号数据重复: ${duplicateMessages.join(', ')}`);
            return; // 阻止表单提交
          }


          this.form.ytElevatorModelsList = this.ytElevatorModelsList;
          if (this.form.brandId != null) {
            updateBrands(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrands(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const brandIds = row.brandId || this.ids;
      this.$modal.confirm('是否确认删除电梯品牌为"' + row.name + '"的数据项？').then(function() {
        return delBrands(brandIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 电梯型号管理序号 */
    rowYtElevatorModelsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 电梯型号管理添加按钮操作 */
    handleAddYtElevatorModels() {
      let obj = {};
      obj.model = "";
      obj.name = "";
      obj.type = "";
      obj.description = "";
      obj.capacity = "";
      obj.speed = "";
      obj.maxFloors = "";
      obj.maxStops = "";
      obj.maxDoors = "";
      obj.factoryNumber = "";
      obj.createdBy = "";
      obj.createdTime = "";
      obj.updatedBy = "";
      obj.updatedTime = "";
      obj.remark = "";
      this.ytElevatorModelsList.push(obj);
    },
    /** 电梯型号管理删除按钮操作 */
    handleDeleteYtElevatorModels() {
      if (this.checkedYtElevatorModels.length == 0) {
        this.$modal.msgError("请先选择要删除的电梯型号管理数据");
      } else {
        const ytElevatorModelsList = this.ytElevatorModelsList;
        const checkedYtElevatorModels = this.checkedYtElevatorModels;
        this.ytElevatorModelsList = ytElevatorModelsList.filter(function(item) {
          return checkedYtElevatorModels.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleYtElevatorModelsSelectionChange(selection) {
      this.checkedYtElevatorModels = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/brands/export', {
        ...this.queryParams
      }, `电梯品牌信息_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
